package home.pb;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

public class TestReference {


    public static void main(String[] args) {
//    强引用
        Object object = new Object();

//        softReference(object);
//        weakReference(object);
        phantomReference(object);
    }

    /**
     * 软引用
     *
     * @param object object
     */
    public static void softReference(Object object) {
        SoftReference<Object> objectSoftReference = new SoftReference<>(object);
        object = null;
        Object obj = objectSoftReference.get();// 有时候会返回null
        System.out.println("obj:" + obj);
    }

    /**
     * 弱引用
     *
     * @param object object
     */
    public static void weakReference(Object object) {
        WeakReference<Object> objectWeakReference = new WeakReference<>(object);
        object = null;
        Object obj = objectWeakReference.get();// 有时候会返回null
        System.out.println("obj:" + obj);
        boolean enqueued = objectWeakReference.isEnqueued();// 是否被GC器标记为即将回收的垃圾
        System.out.println("enqueued:" + enqueued);
    }

    /**
     * 虚引用
     * @param object object
     */
    public static void phantomReference(Object object) {
        PhantomReference<Object> objectPhantomReference = new PhantomReference<>(object, new ReferenceQueue<>());
        object = null;
        Object obj = objectPhantomReference.get();// 有时候会返回null
        System.out.println("obj:" + obj);
        boolean enqueued = objectPhantomReference.isEnqueued();// 是否被GC器标记为即将回收的垃圾
        System.out.println("enqueued:" + enqueued);
    }


}
